package com.android.xunxian.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.xunxian.MyApplication;
import com.android.xunxian.R;
import com.android.xunxian.adapter.XunxAdapter;
import com.android.xunxian.entry.Xunx;
import com.android.xunxian.utils.UConstants;
import com.android.xunxian.utils.Util;
import com.android.xunxian.view.XListView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.xutils.x;
import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by zouqh on 2016/7/16.
 */
public class XunxActivity1 extends Activity implements View.OnClickListener , XListView.IXListViewListener{


    @InjectView(R.id.close)
    ImageView close;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.ritgh_icon)
    ImageView ritghIcon;
    @InjectView(R.id.ritgh_text)
    TextView ritghText;
    XListView listview;
    ProgressDialog dialog;
    private List<Xunx> xunxList;
    private XunxAdapter adapter;//
    private int page=1;
    private int allPage;
    public static XunxActivity1 activity1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xunx_activity);
        activity1=this;
        listview=(XListView)findViewById(R.id.listview);
        ButterKnife.inject(this);
        titleText.setText("巡线计划");
        ritghText.setText("下载");
        close.setOnClickListener(this);
        ritghText.setOnClickListener(this);
        listview.setPullLoadEnable(true);// 向上滑动加载更多开启
        listview.setPullRefreshEnable(true);
        listview.setXListViewListener(this);
        listview.setFooterName("", false);
        xunxList=new ArrayList<>();
        adapter=new XunxAdapter(this,xunxList);
        listview.setAdapter(adapter);
        getDate("");
//        try {
//
//            xunxList =  MyApplication.dbManager.selector(Xunx.class).findAll();
//            if (xunxList != null&&xunxList.size()>0) {
//                    System.out.println(xunxList);
//            }else{
//                ritghText.setVisibility(View.VISIBLE);
//                xunxList=new ArrayList<>();
//                getDate("");
//
//            }
//
//        } catch (DbException e) {
//            e.printStackTrace();
//        }

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(XunxActivity1.this,DeilstXunxActivity.class);
                Bundle bundle=new Bundle();
                bundle.putSerializable("xunx",xunxList.get(position-1));
                intent.putExtras(bundle);
                startActivity(intent);

            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            case R.id.close:
                finish();
                break;
            case R.id.ritgh_text:
                try {
                    MyApplication.dbManager.saveOrUpdate(xunxList);
                    ritghText.setVisibility(View.GONE);
                } catch (DbException e) {
                    e.printStackTrace();
                }
                break;
        }
    }


    public void refsh(){
        page=1;
        xunxList.clear();
        adapter.notifyDataSetChanged();
        getDate("");
    }

    //获取巡线列表
    private void getDate( String type) {
        dialog = ProgressDialog.show(this, null, "加载中...", true, false);
        RequestParams params = new RequestParams(UConstants.XX_PLAN_LIST);
        params.addBodyParameter("LKind", "CBJ");
        params.addBodyParameter("EmpId",UConstants.EmpId);
        params.addBodyParameter("PLANZT", type);
        params.addBodyParameter("PartId", UConstants.PartId );
        params.addBodyParameter("PAGE", page + "");
        params.addBodyParameter("ROWS", "20");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Util.printLog("getMerchants------------onSuccess-----", result);
                if (result.length() > 0) {
                    try {
                        JSONObject object = new JSONObject(result);
                        allPage = Integer.parseInt(object.getString("total"));
                        allPage = (int) Math.ceil((double) allPage / 20);
                        boolean success = object.getBoolean("success");
//                        String msg = object.getString("msg");
                        if (success) {
                            Gson gson = new Gson();
                            Type lt = new TypeToken<List<Xunx>>() {
                            }.getType();
                            List<Xunx> list = gson.fromJson(object.getString("rows").toString(), lt);
                            if (list != null && list.size() > 0) {
                                if (page == allPage) {
                                    listview.setFooterName("", false);
                                } else if (page <= allPage) {
                                    listview.setFooterVisibility(true);
                                }
                                xunxList.addAll(list);
                                adapter.notifyDataSetChanged();

                            } else {
                                Toast.makeText(x.app(), "暂无巡线！", Toast.LENGTH_LONG).show();
                                listview.setFooterName("", false);
                            }

                        } else {
                            Toast.makeText(x.app(), "暂无巡线！", Toast.LENGTH_LONG).show();
                        }
//                        Toast.makeText(x.app(), msg, Toast.LENGTH_LONG).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                dialog.dismiss();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Util.printLog("getMerchants------------onError-----", ex.getMessage() + "");

                Toast.makeText(x.app(), "获取数据失败！", Toast.LENGTH_LONG).show();
                dialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

                Toast.makeText(x.app(), "cancelled", Toast.LENGTH_LONG).show();
                Util.printLog("getMerchants------------onCancelled-----", cex.getMessage() + "");
                dialog.dismiss();
            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 获取下载巡线路线
     */
    private void downXunx() {


        try {


            xunxList =  MyApplication.dbManager.selector(Xunx.class).findAll();
            if (xunxList != null&&xunxList.size()>0) {
                Toast.makeText(x.app(), "下载成功", 10).show();
            }else{
                ritghText.setVisibility(View.VISIBLE);
            }

        } catch (DbException e) {
            e.printStackTrace();
        }
    }



    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (page < allPage) {
                        page++;
                        getDate("");
                    } else {
                        listview.setFooterName("", false);
                    }
                    break;

                case 2:
                    page=1;
                    xunxList.clear();
                    adapter.notifyDataSetChanged();
                    getDate("");
                    onLoad();
                    break;

            }

        }
    };

    @Override
    public void onRefresh() {

        handler.sendEmptyMessage(2);

    }

    @Override
    public void onLoadMore() {
        handler.sendEmptyMessage(1);
        onLoad();


    }

    private void onLoad() {
        listview.stopRefresh();
        listview.stopLoadMore();
        listview.setRefreshTime("刚刚");
    }

}